package com.atguigu.cloud.gateway.filter;

import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author LT
 * @create 2023-11-14-20:36
 */
@Component
public class AuthGatewayFilterFactory implements GatewayFilterFactory<Object> {
    @Override
    public Class<Object> getConfigClass() {
        return Object.class;
    }

    @Override
    public GatewayFilter apply(Object config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                String path = request.getURI().getPath();
                AntPathMatcher matcher = new AntPathMatcher();
                if (!matcher.match("/*/param/**",path)){
                    return chain.filter(exchange);
                }
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.OK);
                response.getHeaders().add("content-type", MediaType.APPLICATION_PROBLEM_JSON_UTF8_VALUE);
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("code",HttpStatus.FORBIDDEN.value());
                jsonObject.addProperty("message","param禁止访问");
                String s = jsonObject.toString();
                DataBuffer buffer = response.bufferFactory().wrap(s.getBytes());

                return response.writeWith(Mono.just((buffer)));
            }
        };

    }
}
